<template>
  <div>
    <MyTable :goodsList="goodsList">
      <template #head>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
      <template #body="scope">
        <td>{{ scope.index + 1 }}</td>
        <td>{{ scope.row.goods_name }}</td>
        <td>{{ scope.row.goods_price }}</td>
        <td>
          <input
            type="text"
            v-if="scope.row.inputVisible === true"
            v-focus
            class="tag-input form-control"
            style="width: 100px;"
            @blur="scope.row.inputVisible = false; scope.row.inputValue = ''"
            v-model="scope.row.inputValue"
            @keydown.enter="addTags(scope.row, scope.row.inputValue)"
          >
          <button
            v-else
            @click="scope.row.inputVisible = true"
            class="btn btn-primary btn-sm add-tag"
            style="display: block;"
          >+Tags</button>
          <span
            v-for="(str, index) in scope.row.tags"
            :key="index"
            class="badge bg-warning text-dark"
          >{{ str }}</span>
        </td>
        <td>
          <button
            class="btn btn-danger btn-sm"
            @click="delFn(scope.row.id)"
          >删除</button>
        </td>
      </template>
    </MyTable>
  </div>
</template>
 
<script>
import MyTable from '@/components/MyTable'
export default {
  components: {
    MyTable
  },
  data() {
    return {
      goodsList: ''
    }
  },
  created() {
    this.$axios({
      url: '/api/goods'
    }).then((res) => {
      this.goodsList = res.data.data
    })
  },
  methods: {
    delFn(id) {
      this.goodsList = this.goodsList.filter((item) => item.id !== id)
    },
    addTags(obj) {
      if (!obj.inputValue.trim().length) return alert('输入内容不能为空')
      obj.tags.push(obj.inputValue)
      obj.inputValue = ''
    }
  },
  directives: {
    focus: {
      inserted(el) {
        el.focus()
      }
    }
  }
}
</script>

<style scoped>
</style>